﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : PhotonServerProject | MasterServer | AccountDeleteResponseHandler.cs
// //  Created : 2016 - 04 - 08 15:02
// //  Modified: 2016 - 04 - 18 09:38
// //  ********************************************************************************

using System;
using ExitGames.Logging;
using NHibernate;
using PhotonServerCommon.Entities.Domain;
using PhotonServerCommon.Enums;
using PhotonServerFramework.Implementation.Database;
using PhotonServerFramework.Implementation.Handler;
using PhotonServerFramework.Interfaces.Handler;
using PhotonServerFramework.Interfaces.Server;
using PhotonServerFramework.Interfaces.Telegram;

namespace MasterServer.Handler.Response
{
    public class AccountDeleteResponseHandler : ServerTelegramHandler
    {
        public override ILogger Logger { get; }
        public override Guid HandlerId { get; set; } = Guid.NewGuid();
        public override HandlerTypes HandlerType => HandlerTypes.Response;
        public override byte HandlerCode => (byte) OperationCodes.Account;
        public override int HandlerSubCode => (int) OperationSubCodes.DeleteAccount;

        private readonly IServerHandlerRegistry _serverHandlerRegistry;

        public AccountDeleteResponseHandler(ILogger logger, IServerHandlerRegistry serverHandlerRegistry)
        {
            _serverHandlerRegistry = serverHandlerRegistry;
            Logger = logger;
        }

        public override bool HandleTelegram(ITelegram telegram, IServerPeer serverPeer)
        {
            bool handled = false;

            Logger.InfoFormat("Trying to handle telegram of type={0} with code={1}, subcode={2}", telegram.Type,
                (OperationCodes) telegram.TelegramCode, (OperationSubCodes) telegram.TelegramSubCode);

            HandlerT handler = null;

            using (ISession session = SessionManager.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        handler = session.QueryOver<HandlerT>()
                            .Where(c => c.HandlerType == (int) TelegramTypes.Response)
                            .And(c => c.HandlerCode == (int) OperationCodes.ForwardResponse)
                            .And(c => c.Application == serverPeer.ServerPeerData.ApplicationId)
                            .And(c => c.ServerHandler == 1)
                            .SingleOrDefault();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Operation failed with: {0}", ex.Message);
                        transaction.Rollback();
                    }
                }
                session.Close();
            }

            if (handler != null)
            {
                Logger.InfoFormat("Found ServerHandler with id={0} on server={1}", handler.HandlerId,
                    handler.ServerId);

                _serverHandlerRegistry.GetServerHandlerById(Guid.Parse(handler.HandlerId))
                    .HandleTelegram(telegram, serverPeer);

                handled = true;
            }
            else
            {
                Logger.ErrorFormat("Could not find server handler!");
            }

            return handled;
        }
    }
}
